<template>
  <div>
    <div class="search">
      <input v-model="keyWords" class="search-input" type="text" placeholder="输入城市名或拼音">
    </div>
    <div class="search-content" ref="search" v-show="keyWords"><!--ref没有（：）冒号-->
        <ul>
          <li class="search-item border-bottom" v-for="item of list" :key="item.id" @click="handleCityClick(item.name)">{{item.name}}</li>
          <li class="search-item border-bottom" v-show="hasNoData">没有匹配到指定数据</li>
        </ul>
    </div>
  </div>

</template>

<script>
  import BScroll from 'better-scroll'
  import {mapMutations} from 'vuex'
  export default {

    name:'CitySearch',
    props:{
      cities:Object,
    },
    data (){
     return {
       keyWords:'',
       list:[],
       timer:null
     }
    },
    methods:{
      handleCityClick (city){
        //改变vuex中的status中的数据需要先调用active  但是调用active前需要调用dispatch
        this.changeCity(city)  //修改数据也可以直接通过mutations  只需要把dispatch换成commit
        this.$router.push('/')
      },
      ...mapMutations(['changeCity'])
    },
    computed:{
      hasNoData (){
        return !this.list.length  //计算属性判断是否有值
      }
    },
    watch:{
      keyWords (){   //必须和要监听的数据名称一样
        if(this.timer){
          clearTimeout(this.timer)
        }
        if(!this.keyWords){//当输入框没有值的时候
          this.list=[]  //数组为空
          return
        }
        this.timer=setTimeout(()=>{
          const result=[]
          for (let i in this.cities){
            this.cities[i].forEach((value)=>{
             if(value.spell.indexOf(this.keyWords) > -1 || value.name.indexOf(this.keyWords) > -1){  //indexOf可以验证传入的字符串与前面的是否包含 不包含返回-1 否则大于-1
               result.push(value)
             }
            })
          }
          this.list = result
        },100)
      }
    },
    mounted (){
      this.scroll = new BScroll(this.$refs.search,{click:true})
    }
  }
</script>

<style lang="stylus" scoped>
  @import "~styles/varibles.styl"
  .search
    height: .72rem
    background $bgColor
    padding 0 .1rem
    .search-input
      box-sizing border-box
      height: .62rem
      line-height: .62rem
      text-align: center
      width 100%
      padding 0 .1rem
      border-radius .06rem
      color #666

  .search-content
    position absolute
    z-index 1
    overflow: hidden
    top: 1.58rem
    left: 0
    right: 0
    bottom: 0
    background #ccc
    .search-item
      line-height: .62rem
      padding-left: .2rem
      background #ffffff
      color #666
</style>
